<template>
  <div class="notice-wrapper" :class="{ 'has-fixed-top-notices': hasFixedTopNotices}"></div>
</template>

<script>
import { createVNode, render } from 'vue'
import { ElAlert, ElMessageBox } from 'element-plus'
import {fetchLatest} from "@/api/system/notice.js";

export default {
  name: "Notice",
  data () {
    return {
      notices: [
        { title: '维护通知', type: 'FIXED_IN_TOP', content: '今晚八点半，桂阳影剧院！' },
        { title: '维护通知', type: 'FIXED_IN_TOP', content: '今晚八点半，桂阳影剧院！' },
      ]
    }
  },
  computed: {
    // 判断是否存在固定在顶部的提示
    hasFixedTopNotices () {
      return this.notices.filter(n => n.type === 'FIXED_TOP').length > 0
    }
  },
  methods: {
    // 获取数据
    fetchLatestNotices () {
      fetchLatest({ count: import.meta.env.VITE_APP_SYSTEM_NOTICE_COUNT })
        .then(data => {
          // 过滤掉已经提示的通知
          this.notices = data.filter(notice => {
            return localStorage.getItem(`NOTICE_${notice.uid}`) == null
          })
          this.renderNotices()
        })
        .catch(e => {
          console.error(e)
          this.$tip.apiFailed('加载系统通知时出现错误，请查看控制台信息！')
        })
    },
    // 渲染通知
    renderNotices () {
      this.$nextTick(() => {
        if (this.notices.length === 0) {
          return
        }
        for (const notice of this.notices) {
          // 固定在顶部提示
          if (notice.type === 'FIXED_TOP') {
            this.createElAlert(notice)
          }
          // 弹窗提示
          if (notice.type === 'POP_UP') {
            this.createElDialog(notice)
          }
        }
      })
    },
    // 创建顶部提示
    createElAlert (notice) {
      const vnode = createVNode(ElAlert, {
        type: 'warning',
        description: `${notice.title}：${notice.content}`,
        closable: true,
        showIcon: false,
        closeText: '知道了',
        onClose: () => {
          render(null, container); // 销毁组件
          localStorage.setItem(`NOTICE_${notice.uid}`, '')
        }
      });
      const container = document.createElement('div');
      this.$el.appendChild(container);
      render(vnode, container);
    },
    // 创建弹窗提示
    createElDialog (notice) {
      ElMessageBox.alert(notice.content, notice.title, {
        type: 'warning',
        confirmButtonText: '知道了'
      })
        .then(() => {
          localStorage.setItem(`NOTICE_${notice.uid}`, '')
        })
        .catch(() => {})
    }
  },
  created () {
    this.fetchLatestNotices()
  }
}
</script>

<style lang="scss">
.notice-wrapper {
  // 存在固定在顶部的提示
  &.has-fixed-top-notices {
    padding: 5px;
  }
  // el-alert父元素
  & > div {
    margin-bottom: 3px;
    &:last-of-type {
      margin-bottom: 0;
    }
  }
  .el-alert {
    box-shadow: 0 0 10px -2px rgba(0,0,0,.25);
    .el-alert__description {
      padding-right: 55px !important;
    }
  }
}
</style>
